import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Spin,
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
} from 'antd';
import moment from 'moment';
import router from 'umi/router';

import XLSX from '../../assets/xlsx.min';
// import * as XLSX from 'xlsx-style';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from './Test.less';

const listernerable = false;
const FormItem = Form.Item;
const { Step } = Steps;
const { TextArea } = Input;
const { Option } = Select;
const RadioGroup = Radio.Group;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const statusMap = ['default', 'processing', 'success', 'error'];

/* eslint react/no-multi-comp:0 */
@connect(({ monitor, loading }) => ({
  monitor,
  loading: loading.models.ruleTest,
}))
@Form.create()
class AStock extends PureComponent {
  state = {
    filterData: [],
    expandForm: false, // 查询菜单栏 是否显示
    listLoading: false,
    formValues: {
      method: 'GetList',
      page: 1,
      pagesize: 200,
      type: 3,
      name: '',
    }, // 查询菜单栏   查询参数
    modalVisible: false,
    updateModalVisible: false,
    selectedRows: [],
    stepFormValues: {},
  };

  columns = [
    {
      title: '股票代码',
      dataIndex: 'code',
      width: 120,
    },
    {
      title: '当前价格',
      dataIndex: 'nowPrice',
      render: text => <span>{text ? `$${text}` : '-'}</span>,
      width: 120,
    },
    {
      title: '交易方向',
      dataIndex: 'tradedirection',
      render: text => <span>{text == 1 ? '卖出' : '买入'}</span>,
      width: 120,
    },
    {
      title: '价格',
      dataIndex: 'price',
      width: 120,
      render: (text, record, index) => (
        <span>{`${record.condition1 == 1 ? '<=' : '>='}${text}`}</span>
      ),
    },
    {
      title: '股数',
      dataIndex: 'count',
      width: 120,
    },
    {
      title: '预估金额',
      dataIndex: 'money',
      width: 120,
    },
    {
      title: '有效期限',
      dataIndex: 'validate',
      width: 120,
    },
    {
      title: '是否成交',
      dataIndex: 'flag',
      width: 120,
      render: text => <span>{text ? '成交' : '-'}</span>,
    },
    {
      title: '归属人',
      dataIndex: 'uploader',
      // filteredValue: null,
      // filters: [
      //   {
      //     text: '花旗',
      //     value: '花旗',
      //   },

      // ],
      // onFilter: (value, record) => {
      //   if (record.uploader != undefined) {
      //     return record.uploader === value;
      //   }
      // },
      // width: 120
    },
  ];

  handleChange(value) {
    const { dispatch } = this.props;
    let param;
    if (value === '今日') {
      param = { type: 1 };
    } else {
      param = {
        type: 1,
        date: value,
      };
    }
    dispatch({
      type: 'monitor/getcodelist',
      payload: param,
    });
  }

  // 默认加载数据-起始方法
  render() {
    const {
      monitor: { data2, codeDateData },
      loading,
      total,
    } = this.props;

    const {
      selectedRows,
      modalVisible,
      updateModalVisible,
      stepFormValues,
      listLoading,
    } = this.state;
    const newdata = {
      list: data2.data,
      pagination: {
        current: this.state.formValues.page,
        pageSize: this.state.formValues.pagesize,
        total: parseInt(data2.total),
      },
    };

    console.log(newdata, 'fdfd');

    const { Option } = Select;

    const children = [];
    if (codeDateData.data.length > 0) {
      children.push(<Option key="今日">今日</Option>);
      for (let i = 0; i < codeDateData.data.length; i++) {
        children.push(
          <Option key={!codeDateData.data[i] ? ' ' : codeDateData.data[i].substring(0, 10)}>
            {!codeDateData.data[i] ? ' ' : codeDateData.data[i].substring(0, 10)}
          </Option>
        );
      }
    }
    return (
      <PageHeaderWrapper title="美股个股成交监控列表">
        <div className={styles.controlBar}>
          <Row>
            <Col xs={24}>
              <Button type="primary" className="optionsbutton" onClick={this.optionsUpload}>
                上传
              </Button>
              <input className="fileipt" type="file" />
              <Button onClick={this.optionsClear}>清空当日</Button>
              <span
                style={{
                  fontSize: 16,
                  // textAlign: 'left',
                  fontWeight: '600',
                  marginLeft: '1em',
                  marginBottom: '4px',
                  height: '32px',
                  lineHeight: '32px',
                }}
              >
                按日期查询
              </span>
              {codeDateData.data.length === 0 ? (
                ''
              ) : (
                <Select
                  defaultValue="今日"
                  style={{ marginLeft: '1em', width: '10em', marginBottom: '4px' }}
                  onChange={this.handleChange.bind(this)}
                >
                  {children}
                </Select>
              )}
            </Col>
            <Col xs={20} />
          </Row>
        </div>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <StandardTable
              rowClassName={this.rowClassName}
              selectedRows={selectedRows}
              loading={listLoading}
              data={newdata}
              columns={this.columns}
              onChange={this.handleStandardTableChange}
              rowKey="id"
              pagination={false}
              scroll={{ y: 650, x: 1000 }}
              bordered
            />
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }

  rowClassName = (record, index) => {
    // return Object.keys(record).length < 5 || record.turnflag ? styles.staticRow : '';

    if (record.flag) return styles.dealRow;
  };

  optionsClear = () => {
    const that = this;
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'monitor/clearcode',
      payload: formValues,
      callback: res => {
        message.success('清空成功!');
      },
    });
  };

  optionsUpload = () => {
    const clearBtn = document.querySelector('.clear_handPanel');
    const that = this;
    document.querySelector('.fileipt').click();
    const $fileipt = document.querySelector('.fileipt');
    // $fileipt.addEventListener('change', uploadExcel);
    if ($fileipt.getAttribute('change') !== '1') {
      $fileipt.setAttribute('change', '1');
      $fileipt.addEventListener('change', uploadExcel);
    }

    function uploadExcel() {
      if (!this.files) {
        return;
      }
      const f = this.files[0];
      parseXLSX(f, function(carData) {
        // $('.optionWatching .optionWatching_btn>input').val('');

        const mapobj = [];
        const submitData = [];
        let iscollected = false;
        for (let i = 0, le = carData.length; i < le; i++) {
          const len = Object.keys(carData[i]).length;
          if (len >= 7 && !iscollected) {
            iscollected = true;
            for (const j in carData[i]) {
              //   console.log(j, carData[i][j]);
              if (carData[i][j].match(/股票代码/)) {
                mapobj.code = j;
              } else if (carData[i][j].match(/当前价格/)) {
                mapobj.nowPrice = j;
              } else if (carData[i][j].match(/价格/)) {
                mapobj.price = j;
              } else if (carData[i][j].match(/股数/)) {
                mapobj.count = j;
              } else if (carData[i][j].match(/预估金额/)) {
                mapobj.money = j;
              } else if (carData[i][j].match(/有效期限/)) {
                mapobj.validate = j;
              } else if (carData[i][j].match(/交易方向/)) {
                mapobj.tradeDirection = j;
              } else if (carData[i][j].match(/归属/)) {
                mapobj.uploader = j;
              }
            }
          } else if (len >= 7 && iscollected) {
            const reg = /(\ )|(\")|(\')|(\r)|(\n)|(\,)/g;
            const submitDataItem = {};

            const { code } = mapobj;
            const { nowPrice } = mapobj;
            const { price } = mapobj;
            const { count } = mapobj;
            const { money } = mapobj;
            const { validate } = mapobj;
            const { tradeDirection } = mapobj;
            const { uploader } = mapobj;
            submitDataItem.condition1 = carData[i][price].match(/>/) ? 0 : 1;
            submitDataItem.code = carData[i][code] || '';
            submitDataItem.nowPrice = carData[i][nowPrice] || '';
            submitDataItem.price = carData[i][price].replace(reg, '').replace(/[^0-9\.]/gi, '') * 1;
            submitDataItem.count = carData[i][count] || '';
            submitDataItem.money = carData[i][money] || '';
            submitDataItem.tradedirection =
              carData[i][tradeDirection].replace(reg, '') === '卖出' ? 1 : 0;
            // submitDataItem.expiration = formatDate(carData[i][expiration]) || '';
            submitDataItem.validate = formatDate(carData[i][validate]) || '';
            submitDataItem.uploader = carData[i][uploader] || '';
            submitData.push(submitDataItem);
          }
        }
        const { dispatch } = that.props;
        const { formValues } = that.state;

        dispatch({
          type: 'monitor/aUploadcode',
          payload: submitData,
          callback: res => {
            $fileipt.value = '';
            message.success('上传成功!');
            dispatch({
              type: 'monitor/getcodelist',
              payload: { type: 1 },
            });
            this.setState({
              listLoading: false,
            });
          },
        });
        console.log(submitData, 'submitData');
      });
      function format(carData) {
        const obj = {};
        const reg = /(\ )|(\")|(\')|(\r)|(\n)|(\,)/g;
        for (let i = 0, len = carData.length; i < len; i++) {
          for (j in carData[i]) {
            if (!obj[j]) {
              obj[j] = [];
            }
            obj[j].push(carData[i][j].replace(reg, ''));
          }
        }
        obj.userId = localStorage.getItem('userid');
        return obj;
      }

      function formatDate(numb) {
        const time = new Date((numb - 1) * 24 * 3600000 + 1);
        time.setYear(time.getFullYear() - 70);
        const year = `${time.getFullYear()}`;
        const month = `${time.getMonth() + 1}`;
        const date = `${time.getDate()}`;
        return `${year}-${month < 10 ? `0${month}` : month}-${
          date < 10 ? `0${date}` : date
        } 00:00:00`;
      }
    }

    function parseXLSX(f, cb) {
      let carData;
      let wb; // 读取完成的数据
      const rABS = false; // 是否将文件读取为二进制字符串
      const reader = new FileReader();
      reader.onload = function(e) {
        const data = e.target.result;
        if (rABS) {
          wb = XLSX.read(btoa(fixdata(data)), {
            type: 'base64',
          });
        } else {
          wb = XLSX.read(data, {
            type: 'binary',
          });
        }
        // carData就是我们需要的JSON数据
        carData = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);

        typeof cb === 'function' && cb(carData);
      };
      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }

      function fixdata(data) {
        // 文件流转BinaryString
        let o = '';
        let l = 0;
        const w = 10240;
        for (; l < data.byteLength / w; ++l)
          o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
        o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
        return o;
      }
    }
  };

  // 加载完 之后 再加载 此 方法
  // componentWillMount() {
  //   const s = document.createElement('script');
  //   s.type = 'text/javascript';
  //   s.src = '../../assets/xlsx.min.js';
  //   document.body.appendChild(s);
  // }
  componentDidMount() {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'monitor/getcodelist',
      payload: { type: 1 },
    });
    dispatch({
      type: 'monitor/CodeDateList',
    });
  }

  // 改变每页条数和当前页
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    formValues.page = pagination.current;
    formValues.pagesize = pagination.pageSize;
    const params = {
      ...formValues,
    };
    dispatch({
      type: 'monitor/GetFundTwoList',
      payload: params,
    });
  };

  // 判断 菜单栏 是 缩放显示 还是 全部展示
  renderForm() {
    const { expandForm } = this.state;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  // 菜单栏- 点击展开显示 事件
  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="最大财报日">
              {getFieldDecorator('maxEarningsDate ')(
                <DatePicker style={{ width: '100%' }} placeholder="请输入最大财报日" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="最小财报日">
              {getFieldDecorator('minEarningsDate')(
                <DatePicker style={{ width: '100%' }} placeholder="请输入最小财报日" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="最小保本幅度">
              {getFieldDecorator('minBreakEvenMargin')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="最小权利金">
              {getFieldDecorator('minRoyalty')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="最小收益率">
              {getFieldDecorator('minYieldRate')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
        </Row>
        <div style={{ overflow: 'hidden' }}>
          <div style={{ marginBottom: 24 }}>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
            <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
              收起 <Icon type="up" />
            </a>
          </div>
        </div>
      </Form>
    );
  }

  // 菜单栏 默认收缩显示 事件
  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="最小权利金">
              {getFieldDecorator('minRoyalty')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="最小收益率">
              {getFieldDecorator('minYieldRate')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <Icon type="down" />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  // 菜单栏-查询按钮 事件
  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    const { formValues } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };
      if (values.maxEarningsDate != undefined) {
        formValues.maxEarningsDate = values.maxEarningsDate;
      }
      if (values.minBreakEvenMargin != undefined) {
        formValues.minBreakEvenMargin = parseFloat(values.minBreakEvenMargin);
      }
      if (values.minEarningsDate != undefined) {
        formValues.minEarningsDate = values.minEarningsDate;
      }
      if (values.minRoyalty != undefined) {
        formValues.minRoyalty = parseFloat(values.minRoyalty);
      }
      if (values.minYieldRate != undefined) {
        formValues.minYieldRate = parseFloat(values.minYieldRate);
      }
    });

    dispatch({
      type: 'monitor/GetRoyaltiesList',
      payload: formValues,
    });
  };

  // 菜单栏- 重置按钮 事件
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    const { formValues } = this.state;
    form.resetFields();
    formValues.maxEarningsDate = '';
    formValues.minBreakEvenMargin = 0;
    formValues.minEarningsDate = '';
    formValues.minRoyalty = 0;
    formValues.minYieldRate = 0;

    dispatch({
      type: 'monitor/GetRoyaltiesList',
      payload: formValues,
    });
  };

  // 菜单栏- 展开 关闭 事件
  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };
}

export default AStock;
